import asyncio
import aiohttp

# requests.get()同步的代码 -> 异步操作aiohttp

urls = [
    'https://img2.woyaogexing.com/2022/05/17/278bc8e41c8d494e9abd8f9efb8b5023!400x400.jpeg',
    'https://img2.woyaogexing.com/2022/05/17/2f206def65f345a39a5d7786d73a36d5!400x400.jpeg',
    'https://img2.woyaogexing.com/2022/05/17/79c5af1866b740bab1b349564827381a!400x400.jpeg'
]


async def aiodpwnload(url):
    """发送请求 得到图片内容 保存文件"""
    name = url.rsplit('/', 1)[1]  # 从右边切 切一次 得到【1】位置的内容
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:  # resp=requests.get()
            with open(name, 'wb') as f:
                f.write(await resp.content.read())  # 读取文件是异步的 需要await挂起
    print('ok')


async def mian():
    tasks = []
    for url in urls:
        d = asyncio.create_task(aiodpwnload(url))
        tasks.append(d)
    await asyncio.wait(tasks)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(mian())
    # asyncio.run(mian())
